<?php 
if (!defined('BASEPATH')){
	exit('No direct script access allowed');
}

/**
 * BookingHistory Controller
 * Build by Phuc Nguyen
 * Contact : nguyenvanphuc0626@gmail.com
 */

class Bookhistory extends BACKEND_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->language('bookhistory');
		$this->load->language('button');
		if($this->database_connect_status){
			$this->load->model('bookhistory_model');
			$this->set_controller('bookhistory');
			$this->set_model($this->bookhistory_model);
		}
                $this->load->library('bookinglib');
                $this->bookinglib = new bookinglib();
                
                $this->load->model('user_model');
	}
        
        private function menuTop(){
            $this->load->model('stats_model');
            $user_info                          = $this->stats_model->get_user_info($this->stats_model->get_user_id());
            $this->view_data['role_by_group']   = $user_info['role_list'];
            $this->view_data['username']        = $user_info['username'];
            return $this->view_data;
        }

        public function updateBill(){
            $this->bookinglib->direct();
            $this->menuTop();
            
            if($this->input->server('REQUEST_METHOD')=='POST'){
                
                $this->view_data["bookhistory"]                                       = new stdClass();
                $this->view_data["bookhistory"]->dkve                                 = $this->input->post('dkve');
                $this->view_data["bookhistory"]->dkhanhly                             = $this->input->post('dkhanhly');
                $this->view_data["bookhistory"]->condition_print                      = ($this->input->post('condition_print') == 'true')?'1':'0';

                $this->load->helper('character');
                $this->load->helper('form');
                $this->load->library('form_validation');
                $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                
                $rules = array(
                    array(
                        'field'   => 'dkve',
                        'label'   =>  $this->lang->line('dkve'),
                        'rules'   => 'trim|max_length[255]|xss_clean'
                    )
                );
                
                $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                $this->form_validation->set_rules($rules);

                if ($this->form_validation->run()==TRUE){
                    $id = $this->input->post('id');
                    $this->bookhistory_model->update($this->view_data["bookhistory"],$id);
                    if($this->input->post('hiddenCty') == 'true'){
                        $hiddenCty = 1;
                    } else {
                        $hiddenCty = 0;
                    }
                    $this->session->set_userdata('hiddenCty', $this->input->post('hiddenCty'));
                    if($id){
                            $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                            $paramAdminLog  = array(
                                'userid'            => $this->session->userdata['user_id'],
                                'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                'ip'                => $_SERVER['REMOTE_ADDR'],
                                'logAction'         => $this->lang->line("update_bill_success").$id,
                                'agent_code'        => $this->session->userdata['agent_code']
                            );
                            $this->user_model->insertUserAdminLog($paramAdminLog);
                    }
                    die($id);
                }
            }
            
            
            $info                                       = $this->bookhistory_model->selectAll($this->input->get('id'),NULL);
            $this->view_data['css']			= array(STATIC_URL.'backend/css/page.css');
            $this->view_data['info']                    = $info[0];
            
            $this->load->view('auth/bookhistory/updatebill', $this->view_data);
        }

        public function printbill(){
            $this->bookinglib->direct();
            $this->load->model('configuration_model');
            $info       = $this->bookhistory_model->find_by(array('id'=>$this->input->get('id')));
            $tmp        = json_decode($info[0]->booking);
            $a          = explode("-",$tmp[0]);

            $nguoilon = explode("||", $info[0]->booking_customer_name);
            if($info[0]->booking_child){
                $child = explode(",",$info[0]->booking_child);
                foreach($child as $vals){
                    $nguoilon[] = trim($vals);
                }
            }
            
            $info       = array(
                'booking_place_code'    =>  $info[0]->booking_place_code,
                'real_fare'             =>  $info[0]->sale_fare,//sale_fare gia thuc ko chinh xac neu booking co du...
                'booking_customer_name' =>  array_chunk($nguoilon, 2),
                'booking'               =>  $tmp,
                'dkve'                  =>  $info[0]->dkve,
                'dkhanhly'              =>  $info[0]->dkhanhly,
                'condition_print'       =>  $info[0]->condition_print,
                'logo'                  =>  substr($a[1],0,2),
                'hiddenCty'             =>  ($this->session->userdata('hiddenCty')=='true')?'1':'0'
            );
            $this->session->unset_userdata("hiddenCty");
            
            $this->view_data['css']			= array(
				STATIC_URL.'backend/css/page.css',
		);
            
            $this->view_data['info']                          = $info;
            $this->view_data['configuration']                 = $this->configuration_model->find_by();
            unset($tmp);unset($a);
            
            $this->load->view('auth/bookhistory/printbill', $this->view_data);
        }
        
        public function export(){
            //export data to excel
               if(isset($_POST['submit']) && $_POST['submit'] == 'export'){
                    $beginTime                      = ($_POST['beginTime'])?date('Y-m-d',strtotime($_POST['beginTime'])):'';
                    $endTime                        = ($_POST['endTime'])?date('Y-m-d',strtotime($_POST['endTime'])):'';
                    $customerID                     = ($_POST['customerID'])?$_POST['customerID']:'';
                    $userid                         = ($_POST['userid'])?$_POST['userid']:$this->session->userdata['user_id'];
                    
                    if($beginTime == "" && $endTime == "" && $customerID == "" && $userid == ""){
                        die(" Vui lòng điền ít nhất 1 thông tin!");
                    }
                    
                    $result =   $this->bookhistory_model->export($beginTime,$endTime,$customerID,$userid);
                    
                    $lists = array();
                    $this->load->model('paymentDebts_model');
                    $this->load->model('voucher_model');
                    $this->load->model('ticketWorkers_model');
                    
                    foreach($result as $k => $values){
                        
                        $_segment       = $values->segments;
                        $paxname    = explode("||",$values->booking_customer_name);
                        if($values->booking_child){
                            $child      = explode(',',$values->booking_child);
                            foreach($child as $keys => $vals){
                                $paxname[] = trim($vals);
                            }
                        }   
                        $tpv_segment   = count($paxname);
                        
                        if($values->voucher_id){
                            $data = array(
                                'booking_place_code'    =>  $values->booking_place_code,
                                'airline'               =>  $values->airline,
                                'createdTime'           =>  $values->createdTime
                            );
                            
                            $getSalefare = $this->voucher_model->getnegative($data,true,false);//gia ban
                            $getRealfare = $this->voucher_model->getnegative($data,false,true);//gia thuc
                            
                            if($getSalefare[0]->sale_fare > $getRealfare[0]->real_fare){
                                continue;
                            } else {
                                $values->real_fare  = $getRealfare[0]->real_fare;
                            }
                            unset($getSalefare);
                            unset($getRealfare);
                            unset($data);
                            //giao ve--
                            //$transporter = $this->bookhistory_model->getNameTicker($values->voucher_id);
                            if($values->payment_method == 2){
                                $transporter = $this->bookhistory_model->getNameTicker($values->voucher_id);
                            } else {
                                $ticketworkers      =   $this->voucher_model->find_by(array('id'=>$values->voucher_id),'ticketworkers');
                                if($ticketworkers[0]->ticketworkers){
                                    $_segment       = $tpv_segment * count(json_decode($values->booking));
                                }
                                $transporter = $this->ticketWorkers_model->find_by(array('id'=>$ticketworkers[0]->ticketworkers));
                            }
                            $transporter = $transporter[0]->name;
                        }
                        
                        if($values->payment_method == 4){
                            $return = $this->paymentDebts_model->find_by(array('booking_id'=>$values->booking_id,'owner'=>180));//chi lay nhung cong no cua pe phong
                            if(empty($return)){
                                continue;
                            }
                        }
                        $json       = json_decode($values->booking);
                        $ngaybay    = explode("-",$json[0]);
                        
                        $phone      = json_decode($values->phone);
                        $phone      = implode("<br/>",$phone);
                        $booking_types  =   $values->booking_types;
                        foreach($json as $key => $vals){
                            $after  = explode("-",$vals);
                            if($key == 0){
                                $ship = $after[3].'-'.$after[5];
                            } else {
                                $pos  = strpos($ship, $after[3]);
                                if ($pos === false) {
                                    //khong tim thay
                                    $ship .= '-'.$after[3];
                                }
                                
                                $pos  = strpos($ship, $after[5]);
                                if ($pos === false) {
                                    //khong tim thay
                                    $ship .= '-'.$after[5];
                                }
                            }
                            $ngayve = '';
                            if($key == count($json)-1 && count($json) > 1){
                                $ngayve = explode("-",$vals);
                                $ngayve = $ngayve[0];
                            }
                        }
                        
                        $lists[] = array(
                            'createdTime'               =>  date('d-m-Y',$values->createdTime),
                            'ngaybay'                   =>  $ngaybay[0],
                            'ngayve'                    =>  ($ngayve)?$ngayve:'',
                            'name'                      =>  $paxname,
                            'ship'                      =>  $ship,
                            'booking_place_code'        =>  $values->booking_place_code,
                            'sove'                      =>  '',
                            'vn'                        =>  ($values->airline=="VN")?"X":'',
                            'vj'                        =>  ($values->airline=="VJ")?"X":'',
                            'bl'                        =>  ($values->airline=="BL")?"X":'',
                            'mk'                        =>  ($values->airline=="MK")?"X":'',
                            'other'                     =>  (in_array($values->airline,array("VN","VJ","BL","MK"))?'':$values->airline),
                            'net_fare'                  =>  $values->net_fare,
                            'price_tpv'                 =>  (($values->airline == "BL" || $values->airline == "VJ") && $booking_types == 1)?$tpv_segment * 5000:'',
                            'profit'                    =>  $values->real_fare - $values->net_fare - $tpv_segment*5000 -$_segment * 3000,
                            'sale_fare'                 =>  $values->real_fare,
                            'note'                      =>  '',
                            'phone'                     =>  $phone,
                            'note'                      =>  $values->note,
                            'giaove'                    =>  $_segment * 3000,
                            'nguoigiaove'               =>  ($transporter)?$transporter:'',
                            'booker'                    =>  $values->username,
                            'payment_method'            =>  $values->payment_name,
                            'segments'                  =>  $_segment,
                            'tpv_segment'               =>  $tpv_segment,
                            'booking_types'             =>  $booking_types
                        );
                    }
                      
                    $this->view_data['lists']   =   $lists;
                    $this->load->view('auth/bookhistory/export', $this->view_data);
               }
        }
        
        public function exportBill(){
            $this->bookinglib->direct();
            $this->menuTop();
            
            if($this->input->server('REQUEST_METHOD')=='POST'){
                
                $this->view_data["bookhistory"]                                         = new stdClass();
                $this->view_data["bookhistory"]->fare                                   = $this->input->post('fare');
                $this->view_data["bookhistory"]->infoBill                               = $this->input->post('infoBill');
                $this->view_data["bookhistory"]->save_contact                           = ($this->input->post('save_contact'))?$this->input->post('save_contact'):'0';
                $this->view_data["bookhistory"]->customerID                             = $this->input->post('customerID');
                $this->view_data["bookhistory"]->agent_code                             = $this->session->userdata['agent_code'];
                $this->view_data["bookhistory"]->owner                                  = $this->session->userdata['user_id'];
                $this->view_data["bookhistory"]->lastupdated                            = date("Y-m-d H:i:s");

                $this->load->helper('character');
                
                $this->load->helper('form');
                $this->load->library('form_validation');
                $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                
                $rules = array(
                    array(
                        'field'   => 'infoBill',
                        'label'   =>  $this->lang->line('infoBill'),
                        'rules'   => 'required|trim|max_length[255]|xss_clean'
                    )
                );
                
                $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                $this->form_validation->set_rules($rules);
                
                if ($this->form_validation->run()==TRUE){
                    $customerID = $this->input->post('customerID');
                    $this->load->model('bookinfobill_model');
                    
                    $bookinfo = $this->bookinfobill_model->find_by(array('customerID' => $customerID,'owner'=>$this->session->userdata['user_id']));
                    
                    if(empty($bookinfo)){
                        $this->bookinfobill_model->create($this->view_data["bookhistory"]);
                    } else {
                        $this->bookinfobill_model->updateInfo($this->view_data["bookhistory"]);
                    }
                    /*
                     * update contacts
                     */
                    if($this->view_data["bookhistory"]->save_contact  == 1){
                        $this->load->model('listcustomers_model');
                        $listcustomer                   = new stdClass();
                        $listcustomer->info_bill        = $this->input->post('infoBill');
                        $this->listcustomers_model->update($listcustomer,'',array('customerID'=>$this->input->post('customerID')));
                    }

                    if($customerID){
                            $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                            $paramAdminLog  = array(
                                'userid'            => $this->session->userdata['user_id'],
                                'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                'ip'                => $_SERVER['REMOTE_ADDR'],
                                'logAction'         => $this->lang->line("update_bill_success").$customerID,
                                'agent_code'        => $this->session->userdata['agent_code']
                            );
                            $this->user_model->insertUserAdminLog($paramAdminLog);
                            
                    }
                }
                unset($paramAdminLog);
                unset($this->view_data["bookhistory"]);
                echo '1';exit;
            }

            $bookhistory_info           = $this->bookhistory_model->find_by(array('booking_id'=>$this->input->get('id')));
            
            $this->view_data['css']     = array(STATIC_URL.'backend/css/page.css');
            $this->view_data['info']    = $this->bookhistory_model->getInfoContactsByParams(array('key'=>'customerID','value'=> $bookhistory_info[0]->customerID));
            $this->load->view('auth/bookhistory/exportbill', $this->view_data);
        }
        
        public function receipt(){
            $this->bookinglib->direct();
            $this->load->model('configuration_model');
            $info       = $this->bookhistory_model->find_by(array('booking_id'=>$this->input->get('id')));
            
            $this->view_data['css']			= array(
				STATIC_URL.'backend/css/page.css',
		);
            
            $this->view_data['info']                          = $info[0];
            $this->view_data['configuration']                 = $this->configuration_model->find_by();
            
            $this->load->view('auth/bookhistory/receipt', $this->view_data);
        }
        
		public function sendsms(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
               
                $p_sms          = $this->input->post('message');
                
                $sms         =  '';
                $sms        .=  ($p_sms['airline'])?$p_sms['airline']." \n":'';
                $sms        .=  'CODE:'.$p_sms['pnr']." \n";
                $sms        .=  implode(" \n",$p_sms['paxname'])." \n";
                $sms        .=  implode(" \n",$p_sms['message'])." \n";
                
                if($this->input->post('showCr') == 1){
                        $sms        .=  'GIA: '.$p_sms['total']." \n";
                }
                if($this->input->post('hanhly')){
                        $sms        .=   'HANH LY:'.$this->input->post('hanhly');
                }

                $params = array(
                    'u'         =>  'PVVIETBAY',
                    'pwd'       =>  'sj688',
                    'from'      =>  'PVVIETBAY',
                    'phone'     =>  $this->input->post('phone'),
                    'sms'       =>  strtoupper(trim($sms))
                );

                $result     = $this->bookinglib->sendsms($params);
                $response   = json_decode($result);

                //sms log
                $this->view_data["telecom"]                             = new stdClass();
                $this->view_data["telecom"]->userid                     = $this->session->userdata['user_id'];
                $this->view_data["telecom"]->phone                      = $this->input->post('phone');
                $this->view_data["telecom"]->message                    = $sms;
                $this->view_data["telecom"]->ipaddress                  = $_SERVER['REMOTE_ADDR'];
                $this->view_data["telecom"]->code                       = $response->result;
                $this->view_data["telecom"]->status                     = $response->error;
                $this->view_data["telecom"]->lastupdated                = date('Y-m-d H:i:s',time());
                $this->view_data["telecom"]->agent_code                 = $this->session->userdata['agent_code'];
                
                $this->load->model('telecom_model');
                $this->telecom_model->create($this->view_data["telecom"]);
                
                echo $response->error;exit;
            }
            $this->load->model('listcustomers_model');
            $this->load->model('bookairport_model');
            
            $booking_info               = $this->bookhistory_model->find_by(array('booking_id' => $this->input->get('id')));
            $listcustomers_query	= $this->listcustomers_model->find_by(array('customerID' => $booking_info[0]->customerID));
            
			$this->view_data['customer']= $listcustomers_query[0]->name;
            $this->view_data['phone']   = json_decode($listcustomers_query[0]->phone);

            //info customers
            $this->view_data['paxname']     = explode("||", $booking_info[0]->booking_customer_name);
            if($booking_info[0]->booking_child){
               $child = explode(',',$booking_info[0]->booking_child);
               foreach($child as $keys => $vals){
                   $this->view_data['paxname'][] = trim($vals);
               }
            }
            $content                        = '';
            $noidung                        = array();
            foreach(json_decode($booking_info[0]->booking) as $key => $vals){
                $info       = explode("-", $vals);
                
                $sbdi       = $this->bookairport_model->find_by(array('code'=>trim($info[3])));
                if(empty($sbdi)){
                        $content               = json_decode(file_get_contents(PRE_API_AIRPORT.trim($info[3]).'?isDestination=false&ccy=VND'));
                        $_info      = array(
                            'code'         =>  trim($content[0]->PlaceId),
                            'city'         =>  trim($content[0]->CityName),
                            'cityEn'       =>  trim(str_replace("City", "", $content[0]->CityNameEn)),
                            'country'      =>  trim($content[0]->CountryName),
                            'countryEn'    =>  trim($content[0]->CountryName)
                        );
                        $this->bookairport_model->create($_info);
                        unset($_info);unset($content);
                }
                $sbdi       = trim($sbdi[0]->cityEn);
                $giodi      = str_replace(':','h',trim($info[2]));
                
                $sbden      = $this->bookairport_model->find_by(array('code'=>trim($info[5])));
                if(empty($sbden)){
                        $content               = json_decode(file_get_contents(PRE_API_AIRPORT.trim($info[5]).'?isDestination=false&ccy=VND'));
                        $_info      = array(
                            'code'         =>  trim($content[0]->PlaceId),
                            'city'         =>  trim($content[0]->CityName),
                            'cityEn'       =>  trim(str_replace("City", "", $content[0]->CityNameEn)),
                            'country'      =>  trim($content[0]->CountryName),
                            'countryEn'    =>  trim($content[0]->CountryName)
                        );
                        $this->bookairport_model->create($_info);
                        
                        unset($_info);unset($content);
                }
                $sbden          = trim($sbden[0]->cityEn);
                
                $times          = explode('/', $info[0]);
                $noidung[]      .=  $sbdi.'-'.$sbden.', ngay '.$times[0].'/'.$times[1].' luc '.$giodi.' '.$info[1];
            }
            
            switch ($booking_info[0]->airline){
                case 'VN':
                    $title = 'VIETNAMAIR';break;
                case 'VJ':
                    $title = 'VIETJET';break;
                case 'BL':
                    $title = 'JESTAR';break;
                default :
                    $title = '';break;
            }
            
            $response     = array(
                'airline'   =>      $title,
                'pnr'       =>      $booking_info[0]->booking_place_code,
                'paxname'   =>      $this->view_data['paxname'],
                'message'   =>      $noidung,
                'total'     =>      $this->bookinglib->my_number_format($booking_info[0]->sale_fare,2, ',', ',').'VNĐ'
            );
            
            if($booking_info[0]->owner != $this->session->userdata['user_id'] && $this->session->userdata['group_id'] != 1){
                $this->view_data['checker']     =   false;
            } else {
                $this->view_data['checker']     =   true;
            }
            
            $this->view_data['noidung'] = json_encode($response);
            $this->load->view('auth/bookhistory/sendsms', $this->view_data);
        }
        
        public function revenues(){
            $this->bookinglib->direct();
            
            $this->load->model('booking_model');
            $revenues                                   = $this->bookhistory_model->revenues($this->session->userdata['user_id']);
            $this->view_data['doanhthu']                = $revenues[0]->real_fare - $revenues[0]->net_fare - ($revenues[0]->segments * 3000);
            $this->view_data['bookinghold']             = $this->booking_model->bookinghold($this->session->userdata('user_id'));
            $this->view_data['bookingOk']               = $this->bookhistory_model->bookingOk($this->session->userdata('user_id'));
            
            $this->load->view('auth/bookhistory/revenues', $this->view_data);
        }
        
        public function receipt_test(){
            $this->view_data = array();
            $this->load->view('auth/bookhistory/receipt_test', $this->view_data);
        }
        
        public function checker(){
                if($this->input->server('REQUEST_METHOD')=='POST' && $this->input->post("session_vb")){
                    $checker = $this->bookhistory_model->find_by(array('id'=>$this->input->post('id'),'checker'=>NULL));
                    if(empty($checker)){
                        die("1");
                    } else {
                        $this->view_data["checker"]                  = new stdClass();
                        $this->view_data["checker"]->checker          = $this->session->userdata['user_id'];
                        $this->bookhistory_model->update($this->view_data["checker"],$this->input->post('id'));
                    }
                    die("0");
                }
                $this->view_data['checker'] = $this->bookhistory_model->find_by(array('booking_id'=>$this->input->get('id')));
                $this->load->view('auth/bookhistory/checker', $this->view_data);
        }
        
        public function noteFly(){
                
                $this->load->model('flyTomorrow_model');
                
                if($this->input->server('REQUEST_METHOD')=='POST' && $this->input->post("session_vb")){
                    
                    
                    $this->view_data["flyTomorrow"]                     = new stdClass();
                    $this->view_data["flyTomorrow"]->note               = ($this->input->post('note'))?trim($this->input->post('note')):'';
                    $info                                               = $this->flyTomorrow_model->find_by(array('booking_place_code'=>$this->input->post('booking_place_code'),'airline'=>$this->input->post('airline')));

                    $this->flyTomorrow_model->update($this->view_data["flyTomorrow"],$info[0]->id);
                    unset($info);unset($this->view_data["flyTomorrow"]);
                    die("1");
                }
                $info                       = $this->bookhistory_model->find_by(array('booking_id'=>$this->input->get('id')));
                $flyTomorrow                = $this->flyTomorrow_model->find_by(array('booking_place_code'=>$info[0]->booking_place_code,'airline'=>$info[0]->airline));

                $this->view_data['info']    = $info;
                $this->view_data['note']    = $flyTomorrow[0]->note;
                $this->load->view('auth/bookhistory/note', $this->view_data);
        }
}